"""
    Created By Khun on 2020/4/11
"""
from sqlalchemy import desc

__author__ = 'Khun'

from flask import render_template, request, redirect, url_for, abort, flash, current_app
from flask_login import login_required

from app.forms.wechat import TypesForm
from app.models import Types, db, Throw
from app.vipadmin import vipadmin


@vipadmin.route('/types/list/<int:page>', methods=['GET', 'POST'])
@login_required
def types_list(page):
    """ 分类列表 """
    page_data = Types.query.paginate(page=page, per_page=current_app.config['PAGE_SIZE'])
    return render_template('types/types_list.html', page_data=page_data)


@vipadmin.route('/types/add', methods=['GET', 'POST'])
@login_required
def types_add():
    """ 分类添加 """
    form = TypesForm()

    if request.method == 'POST' and form.validate_on_submit():
        types = Types()
        types.set_attr(form.data)
        with db.auto_commit():
            db.session.add(types)
        flash('添加成功', 'success')
        return redirect(url_for('vipadmin.types_list', page=1))
    elif form.errors:
        flash('检查数据是否有误', 'danger')

    return render_template('types/types_add.html', form=form)


@vipadmin.route('/types/delete/<int:tid>', methods=['GET', 'POST'])
@login_required
def types_delete(tid):
    """ 分类删除 """
    type_obj = Types.query.filter_by(tid=tid).first()
    if request.method == 'POST' and type_obj is None:
        abort(404)
    with db.auto_commit():
        db.session.delete(type_obj)
    flash('删除成功', 'success')
    return redirect(url_for('vipadmin.types_list', page=1))


@vipadmin.route('/types/edit/<tid>', methods=['GET', 'POST'])
@login_required
def types_edit(tid):
    """ 分类修改 """
    type_obj = Types.query.filter_by(tid=tid).first()

    if request.method == 'POST' and type_obj is None:
        abort(404)
    data = TypesForm(obj=type_obj)

    if request.method == 'POST' and data.validate_on_submit():
        type_obj.set_attr(data.data)
        with db.auto_commit():
            db.session.add(type_obj)
        flash('修改成功', 'success')
        return redirect(url_for('vipadmin.types_list', page=1))
    elif data.errors:
        flash('检查数据是否有误', 'danger')

    return render_template('types/types_edit.html', data=data, type_obj=type_obj)


@vipadmin.route('types/<int:type_tid>/all/<int:page>')
def types_all(type_tid, page):
    """ 查询每个分类对应的模板 """
    page_data = Types.query.get(type_tid).type_tem.order_by(desc(Throw.tid)).paginate(
        page=page, per_page=current_app.config['PAGE_SIZE']
    )
    return render_template('throw/search_type_all.html', page_data=page_data, type_tid=type_tid)
